/* eslint-disable react-refresh/only-export-components */
import { Form, useLoaderData, useActionData } from 'react-router';

export function loader({ params }: { params: { contactId: string } }) {
  return fetch(`/api/contacts/${params.contactId}`).then((res) => res.json());
}

export function action({ request, params }: { request: Request; params: { contactId: string } }) {
  return request.formData().then((formData) => {
    return fetch(`/api/contacts/${params.contactId}`, {
      method: 'POST',
      body: formData,
    }).then((res) => res.json());
  });
}

export default function Contact() {
  const contact = useLoaderData();
  const actionData = useActionData();
  return (
    <div>
      <h2>{contact.name}</h2>
      <Form method="post">
        <input type="text" name="name" defaultValue={contact.name} />
        <button type="submit">Save</button>
      </Form>
      {actionData && <p>{actionData.message}</p>}
    </div>
  );
}
